package one.stand.controller.index;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.jmp.api.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.feign.TicketFeign;
import com.jmp.service.api.admin.dto.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.common.cache.CrmAppBaseCacheModel;
import one.stand.dto.*;
import one.stand.model.ResultModel;
import one.stand.service.CompanyBaseService;
import one.stand.service.user.UserAdminService;
import one.stand.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@Api(description = "奖券管理")
@RestController
@RequestMapping("/ticket")
public class TicketController {
    @Autowired
    private TicketFeign ticketFeign;

    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private RedisUtil redisUtil;

    @ApiOperation("1首页")
    @GetMapping
    @SecurityAuthCheck(checkPhone = true)
    public ResultModel<TicketIndexResponse> index() {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        TicketIndexCacheModel ticketIndexCacheModel = new TicketIndexCacheModel(redisUtil, optUser.getUserId());
        TicketIndexResponse response = ticketIndexCacheModel.get();
        if (Objects.nonNull(response)) return ResultModel.success(response);

        ResultModel<TicketOrderCountVo> resultModel = ticketFeign.orderCount(TicketOrderCountDto.builder().userId(optUser.getUserId()).build());
        AssertUtil.isTrue(resultModel);
        TicketOrderCountVo vo = resultModel.getData();
        response = TicketIndexResponse.builder()
                .cardUrl("https://file.hongmushichang.com/0/zhibodating/ticket-card2.jpg")
                .activityDetails("      中国·花园红木节\n" +
                        "\n" +
                        "      请于订单上传截至日期之前，将展销会专用销售单上传到抽奖系统。抽奖当天由本人使用”花园购“APP进行现场核销、抽奖，过期奖券作废。特等奖至四等奖，需由本人亲自携带核销手机、中奖奖券、身份证原件进行复核后发放。\n" +
                        "\n" +
                        //"订单上传时间：即日起至2020/9/9/12:00\n" +
                        //"现场抽奖时间：2020/9/10/9:00-16:00\n" +
                        "现场抽奖地址：中国花园红木家具城")
                .orderCount(vo.getOrderCount())
                .title("已通过：" + vo.getAgreeCount() + "  审核中：" + vo.getAuditingCount() + " 未通过：" + vo.getRefuseCount())
                .build();

        ticketIndexCacheModel.save(response);

        return ResultModel.success(response);
    }

    @ApiOperation("2我的订单-列表")
    @GetMapping("order/list")
    @SecurityAuthCheck(checkPhone = true)
    public ResultModel<TicketOrderListResponse> orderList(@RequestAttribute PageRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        TicketOrderListCacheModel cacheModel = new TicketOrderListCacheModel(redisUtil, optUser.getUserId());
        TicketOrderListResponse response = cacheModel.get();
//        if (Objects.nonNull(response)) return ResultModel.success(response);

        TicketOrderListDto dto = TicketOrderListDto.builder()
                .userId(optUser.getUserId())
                .build();
        dto.setPageInit(request.getPageNum(), request.getPageSize());
        ResultModel<TicketOrderListVo> resultModel = ticketFeign.orderList(dto);
        AssertUtil.isTrue(resultModel);
        PageResponse2<TicketOrderListResponse.Order> page = ConvertUtils.page2(resultModel.getData().getPage(), order -> {
            Company2Dto company = companyBaseService.get2(order.getFromCompanyId());
            return TicketOrderListResponse.Order.builder()
                    .orderId(order.getId())
                    .fromCompanyName(company.getCompanyName())
                    .orderNo("订单编号：" + order.getId())
                    .orderMoney(order.getOrderMoney())
                    .ctime(order.getCtime())
                    .fileUpload("已上传")
                    .status(order.getStatus() == 2 ? "未通过原因：" + order.getMemo() : (order.getStatus() == 1 ? "已通过审核" : "订单审核中"))
                    .statusType(order.getStatus())
                    .build();
        });

        ResultModel<TicketOrderCountVo> resultModel2 = ticketFeign.orderCount(TicketOrderCountDto.builder().userId(optUser.getUserId()).build());
        AssertUtil.isTrue(resultModel2);

        response = TicketOrderListResponse.builder()
                .orders(page)
                .title("已通过：" + resultModel2.getData().getAgreeCount() + "  审核中：" + resultModel2.getData().getAuditingCount() + " 未通过：" + resultModel2.getData().getRefuseCount())
                .build();

        cacheModel.save(response);

        return ResultModel.success(response);
    }

    @ApiOperation("2我的订单-编辑-企业列表")
    @GetMapping("order/company/list")
    @SecurityAuthCheck
    public ResultModel<TicketOrderCompanyListResponse> orderList(@RequestAttribute TicketOrderCompanyListRequest request) {
        PageHelper.startPage(1, 20);
        List<CompanyDto> list = companyBaseService.selectTicketCompanyList(request.getKeyword());
        List<TicketOrderCompanyListResponse.Company> page = ConvertUtils.list(list, companyDto -> {
            return TicketOrderCompanyListResponse.Company.builder()
                    .companyId(companyDto.getCompanyId())
                    .companyName(companyDto.getCompanyName())
                    .build();
        });

        TicketOrderCompanyListResponse response = TicketOrderCompanyListResponse.builder()
                .companies(page)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("2我的订单-详情")
    @GetMapping("order/info")
    @SecurityAuthCheck(checkPhone = true)
    public ResultModel<TicketOrderInfoResponse> orderInfo(@RequestAttribute TicketOrderInfoRequest request) {

        ResultModel<TicketOrderInfoVo> resultModel = ticketFeign.orderInfo(TicketOrderInfoDto.builder().orderId(request.getOrderId()).build());
        AssertUtil.isTrue(resultModel);

        TicketOrderInfoVo vo = resultModel.getData();
        Company2Dto company = companyBaseService.get2(vo.getFromCompanyId());
        TicketOrderInfoResponse response = TicketOrderInfoResponse.builder()
                .orderId(vo.getId())
                .fromCompanyId(vo.getFromCompanyId())
                .fromCompanyName(company.getCompanyName())
                .orderNo(vo.getOrderNo())
                .orderMoney(vo.getOrderMoney())
                .photo(vo.getPhoto())
                .payPhoto(vo.getPayPhoto())
                .status(vo.getStatus())
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("2我的订单-上传或修改订单")
    @PostMapping("order/save")
    @SecurityAuthCheck(checkPhone = true)
    public ResultModel orderSave(@RequestAttribute com.jmp.api.dto.TicketOrderSaveRequest request) {

        AssertUtil.nonNull(request.getPhoto(), ResultEnum.PARAM_CHECK, "核销票为空");
        AssertUtil.nonNull(request.getOrderNo(), ResultEnum.PARAM_CHECK, "校验编号不能为空");
        AssertUtil.isTrue(Objects.nonNull(request.getOrderMoney()) && request.getOrderMoney().compareTo(BigDecimal.ZERO) > 0, ResultEnum.PARAM_CHECK, "进货金额不能为空且必须大于零");

//        RequestContext.User user = RequestContextHolder.getRequestContext().getUser();
//        int count = ticketApiJxsMapper.selectJxs(user.getCompanyId(), "经销商花园购");
//        AssertUtil.isTrue(count > 0, ResultEnum.PARAM_CHECK, "非花园购经销商，无法提交订单！如有疑问请联系：0579-86669669");

        com.jmp.service.api.admin.dto.TicketOrderSaveRequest saveRequest = com.jmp.service.api.admin.dto.TicketOrderSaveRequest.builder()
                .id(request.getOrderId())
                .fromCompanyId(request.getFromCompanyId())
                .orderMoney(request.getOrderMoney())
                .orderNo(request.getOrderNo())
                .photo(request.getPhoto())
                .payPhoto(request.getPayPhoto())
                .build();
        ResultModel resultModel = ticketFeign.orderSave(saveRequest);
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation("3我的兑奖码")
    @GetMapping("qr")
    @SecurityAuthCheck(checkPhone = true)
    public ResultModel<TicketQrResponse> qr() {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ResultModel<TicketInfoQrResponse> qrResponseResultModel = ticketFeign.infoQr(TicketInfoQrRequest.builder().userId(optUser.getUserId()).build());
        AssertUtil.isTrue(qrResponseResultModel);
        TicketInfoQrResponse qrResponse = qrResponseResultModel.getData();
        UserDto userDto = userAdminService.get(optUser.getUserId());

        Date now = new Date();
        int status;
        String memo;
        if (qrResponse.getStartTime().after(now)) {
            status = 0;
            memo = "订单上传正在进行中，请于活动时间内及时上传订单。如遇订单审核失败，或上传遇到问题，请至花园红木家具城B区客服中心！";
        } else if (qrResponse.getStartTime().before(now) && qrResponse.getEndTime().after(now) && qrResponse.getStatus() == 0) {
            status = 1;
            memo = "抽奖人手机号: " + userDto.getPhone() + "\n"
                    + "该二维码在" + DateUtil.format(new Date(qrResponse.getQrEndTimes()), "yyyy年MM月dd日HH点mm分钟") + "内有效\n"
                    + "提示：抽奖活动已开始，请及时至活动现场兑换抽奖券，过期奖券将自动作废，兑换奖券时向工作人员出示本二维码即可，二维码" + qrResponse.getQrTimes() + "秒会自动刷新。";
        } else if (qrResponse.getStatus() == 1) {
            status = 2;
            memo = "抽奖人手机号: " + userDto.getPhone() + "\n"
                    + "提示：您的奖券已成功兑换，请在有效期内及时使用，过期未使用奖券将作废，无法参加抽奖活动！";
        } else {
            status = 3;
            memo = "本届花园红木节已圆满结束，期待我们来年再会！";
        }

        TicketQrResponse response = TicketQrResponse.builder()
                .status(status)
                .startTime(qrResponse.getStartTime().getTime() - now.getTime())
                .memo(memo)
                .orderMoney(MoneyUtil.getMoneyStr(qrResponse.getOrderMoney()))
                .ticketCount(qrResponse.getNum())
                .qrCode(qrCode(status, qrResponse.getQrCode()))
                .qrTime(qrResponse.getQrTimes())
                .build();
        return ResultModel.success(response);
    }

    private String qrCode(Integer status, String qrCode) {
        if (status == 0) {
            return "https://file.hongmushichang.com/0/zhibodating/ticket_ing.png";
        } else if (status == 2) {
            return "https://file.hongmushichang.com/0/zhibodating/ticket_ed.png";
        } else if (status == 3) {
            return "https://file.hongmushichang.com/0/zhibodating/ticket_end.png";
        }
        return qrCode;
    }

    private static class TicketIndexCacheModel extends CrmAppBaseCacheModel<TicketIndexResponse> {

        public TicketIndexCacheModel(RedisUtil redisUtil, Integer userId) {
            super(redisUtil, "ticketIndex@" + userId);
        }
    }

    private static class TicketOrderListCacheModel extends CrmAppBaseCacheModel<TicketOrderListResponse> {

        public TicketOrderListCacheModel(RedisUtil redisUtil, Integer userId) {
            super(redisUtil, "ticketList@" + userId);
        }
    }
}
